//
//  DYWOauthController.swift
//  sinaWeibo
//
//  Created by 董艳武 on 16/2/14.
//  Copyright © 2016年 董艳武. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class DYWOauthController: UIViewController,UIWebViewDelegate {
    
    
    
    let webView = UIWebView()
    
    override func loadView() {
        
     
        
        view = webView
        
        webView.delegate = self
        
        setUpNav()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
       

        // 跳转页面的时候一定要注意控制器的 view 的背景颜色
        view.backgroundColor = UIColor.orangeColor()
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=2280038482&redirect_uri=http://www.baidu.com")
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
// 扩展 extension (类似OC中的分类, 但Swift中没有名字), 即在没有权限获取到原始代码的情况下, 为类增加新功能.
// 注意: 只要定义了扩展, 那么该扩展对该类的实例都是可用的.

// MARK:--设置导航栏的样式和导航栏按钮的点击事件
extension DYWOauthController {
    /// 设置导航栏按钮
    private func setUpNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickToDismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickToAutoFill")
        
        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
    }
    /// 实现导航栏按钮的点击事件
    func didClickToDismiss () {
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    func didClickToAutoFill () {
        // document.getElementById('userId').value = "6165258926@163.com";document.getElementById('passwd').value = "dong.6165258926+"
        // \ 转义字符
        let js = "document.getElementById('userId').value = \"6165258926@163.com\";document.getElementById('passwd').value = \"dong.6165258926+\""
        // 让 webview 加载账号密码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}
// MARK:--设置加载视图
extension DYWOauthController {
       // 开始导入
    func webViewDidStartLoad(webView: UIWebView) {
        // 显示加载页面
        SVProgressHUD.show()
    }
    // 结束导入
    func webViewDidFinishLoad(webView: UIWebView) {
        // 加载页面消失
        SVProgressHUD.dismiss()
    }
    // 出现错误
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        // 加载页面消失
        SVProgressHUD.dismiss()
    }
}
// MARK:--获取数据 加载数据 拦截请求 获取 code
extension DYWOauthController {
    // 进行网络请求前的询问
    // 返回 true 让 webview 加载 ， 返回 false 就是进行拦截
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let url = request.URL?.absoluteString {
            
            if url.hasPrefix(redirect_URL) {
                
                if let code = request.URL?.query {
                    // 第一步 截获 code
                    let subStr = code.substringFromIndex("code=".endIndex)
                    // 第二步 获取 token
//                    let viewModel = DYWOauthViewModel()
                    DYWOauthViewModel.sharedInstance.loadData(subStr, success: { () -> () in
                        print("成功")
                        // dismiss 自身
                        self.dismissViewControllerAnimated(true, completion: { () -> Void in

                        })
                        // 切换控制器
                        // FIXME:--改为通知的方式
//                        UIApplication.sharedApplication().keyWindow?.rootViewController = DYWMainController()
                        // MARK:--发送通知
                        NSNotificationCenter.defaultCenter().postNotificationName(choseController, object: nil)
                        }, failure: { (error) -> () in
                             print("失败",error)
                    })

                }
                // 返回 true 会加载百度页面，返回 false 则不会加载百度页面
                return false
                
            }
            
        }
        
        return true
    }

}